#include <stdio.h>      
#include <unistd.h>     
#include <string.h>     
#include <stdint.h>      
#include "iot_i2c.h"
#include "iot_errno.h"
#define AHT20_I2C_IDX         0
#define IR_READ_ADDR      (0x7F<<1 |0x1)
#define IR_WRITE_ADDR     (0x7F<<1 |0x0)
// #define IR_READ_ADDR      0x7F
// #define IR_WRITE_ADDR     0x7F
#define RESET              0x30
#define DATA_READY          0x2


uint32_t IR_Read(uint8_t *buffer, uint32_t buffLen)
{
    // printf("IR_Read start \n");
    uint32_t retval = IoTI2cRead(AHT20_I2C_IDX,     // 指定I2C总线ID
                                 IR_READ_ADDR,   // 指定读地址
                                 buffer,            // 指定读取数据的缓冲区
                                 buffLen);          // 指定读取数据的长度
    if (retval != IOT_SUCCESS)                      // 读取失败
    {
        printf("I2cRead() failed, %0X!\n", retval);
        return retval;
    }
    return IOT_SUCCESS;
}


 uint32_t IR_Write(uint8_t *buffer, uint32_t buffLen)
{
    // printf("IR_Write start \n");
    uint32_t retval = IoTI2cWrite(AHT20_I2C_IDX,    // 指定I2C总线ID
                                  IR_WRITE_ADDR, // 指定写地址
                                  buffer,           // 指定写入数据的缓冲区
                                  buffLen);         // 指定写入数据的长度
    if (retval != IOT_SUCCESS)                      // 写入失败
    {
        printf("I2cWrite() failed, %0X!\n", retval);
        return retval;
    }
    return IOT_SUCCESS;
}

uint32_t Data_Ready (void)
{
    // printf("Data_Ready start \n");
    uint8_t reset[2] = { 0x30,0x00};
    IR_Write(reset,sizeof(reset));
    reset[1] = 0x08;
    
    return  IR_Write(reset,sizeof(reset));
}

uint32_t StartMeasurement(uint8_t *data)
{
    uint32_t retval;
    // printf("StartMeasurement \n");
    uint8_t tmp=0x00;
    uint8_t cmd = 0x10;
    IR_Write(&cmd,1);
    retval=IR_Read(&tmp,1);
    if(retval!=IOT_SUCCESS)
    {
        printf("read 0x10 error \n");
    }
    // printf("0x10:%d",tmp);
    data[0]=tmp;

    usleep(20*1000);

    cmd = 0x11;
    tmp=0x00;
    IR_Write(&cmd,1);
    retval=IR_Read(&tmp,1);
    if(retval!=IOT_SUCCESS)
    {
        printf("read 0x11 error \n");
    }
    data[1]=tmp;

    usleep(20*1000);
    
    cmd= 0x12;
    tmp=0x00;
    IR_Write(&cmd,1);
    IR_Read(&tmp,1);
    data[2]=tmp;

}